package com.able.wanandroid.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;

import com.able.wanandroid.BuildConfig;
import com.able.wanandroid.app.MyApplication;

import java.io.File;

/**
 * @author Administrator
 * @date 2017/11/28
 */

public class AppUtils {
    private static MyApplication mContext = MyApplication.getInstance();

    public static String getVersionName() {
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo info = pm.getPackageInfo(mContext.getPackageName(), 0);
            String versionName = info.versionName;
            LogUtils.i("versionName == " + versionName);
            return versionName;
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("can't find versionName");
            return "";
        }
    }

    public static int getVersionCode() {
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo info = pm.getPackageInfo(mContext.getPackageName(), 0);
            int versionCode = info.versionCode;
            LogUtils.i("versionCode == " + versionCode);
            return versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("can't find versionCode");
            return -1;
        }
    }

    @SuppressLint("MissingPermission")
    public static String getIMEI() {
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        String imei;
        if (tm.getDeviceId() != null) {
            imei = tm.getDeviceId();
        } else {
            //android.provider.Settings;
            imei = Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        return imei;
    }

    public static void callPhone(Context context, String phoneNo) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNo));
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        context.startActivity(intent);
    }


    /**
     * 安装apk
     * 版本大于24，需要通过FileProvider获取文件
     *
     * @param context
     */
    public static void installAPP(Context context) {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "ShiShiBang.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            doInstall(context, file, intent);
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 安装apk
     * 版本大于24，需要通过FileProvider获取文件
     *
     * @param context
     */
    public static void installAPP(Context context, long downloadApkId) {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "ShiShiBang.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean canInstalls = context.getPackageManager().canRequestPackageInstalls();
                if (canInstalls) {
                    doInstall(context, file, intent);
                } else {
                    /**
                     * 请求安装未知应用来源的权限
                     * onRequestPermissionsResult() -->处理回调
                     */
                    ActivityCompat.requestPermissions((Activity) context,
                            new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES},
                            10011);
                }
            } else {
                doInstall(context, file, intent);
            }

        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);

    }

    private static void doInstall(Context context, File file, Intent intent) {
        Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    }


    /**
     * 拍照方法
     *
     * @param context
     */
    public static void takePhoto(Context context) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //Android7.0以上URI
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //通过FileProvider创建一个content类型的Uri
            File file = new File("pathname");
            if (file.exists()) {
            }
            Uri uri = FileProvider.getUriForFile(context, "packageName", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("pathname")));
        }
    }


}
